package schoolmath.web.components.content;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import schoolmath.web.entities.Presentation;
import schoolmath.web.entities.UserGroup;
import schoolmath.web.services.UserService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RequiresRoles(value = {"Администратор", "Преподаватель", "Студент"}, logical = Logical.OR)
public class ShowPresentationsContent {

	private static Logger logger = LoggerFactory.getLogger(ShowPresentationsContent.class);
	@Inject
	private Session session;
	@Inject
	private UserService userService;
	private List<Presentation> activePresentations;
	private Presentation activePresentation;
	@InjectComponent
	private PlayPresentationContent playPresentationContent;

	@SuppressWarnings("unchecked")
	private List<Presentation> getMyGroupActivePresentations() {
		List<UserGroup> myUserGroups = session
				.createQuery("select ugu.userGroup from UserGroupUnit ugu where ugu.user = :user")
				.setParameter("user", userService.getUser())
				.list();
		if (myUserGroups != null && myUserGroups.size() != 0) {
			return session.createQuery("select p from Presentation p where p.currentUserGroup in (:userGroups)")
					.setParameterList("userGroups", myUserGroups)
					.list();
		} else {
			return new ArrayList<>();
		}
	}

	@SuppressWarnings("unchecked")
	private List<Presentation> getMyOwnActivePresentations() {
		return session
				.createQuery("select p from Presentation p where p.owner = :owner and p.playing = true")
				.setParameter("owner", userService.getUser())
				.list();
	}

	@SuppressWarnings("unchecked")
	public List<Presentation> getActivePresentations() {
		if (activePresentations == null) {
			activePresentations = new ArrayList<>();
			activePresentations.addAll(getMyGroupActivePresentations());
			activePresentations.addAll(getMyOwnActivePresentations());
			Set<Presentation> set = new HashSet<>(activePresentations);
			activePresentations = new ArrayList<>(set);
		}
		return activePresentations;
	}

	public Presentation getActivePresentation() {
		return this.activePresentation;
	}

	public void setActivePresentation(Presentation activePresentation) {
		this.activePresentation = activePresentation;
	}

	public Object onRefreshPage() {
		return this;
	}

	public Object onWatch(Presentation presentation) {
		playPresentationContent.setPresentation(presentation);
		return playPresentationContent;
	}

}
